package logic

import (
	"context"
	"fmt"
	"house/models/cache"
	"house/models/mysql"
	"math/rand"
	"strconv"

	"house/houserpc/houserpc"
	"house/houserpc/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type LoginLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginLogic {
	return &LoginLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *LoginLogic) Login(in *houserpc.LoginRequest) (*houserpc.LoginResponse, error) {
	// todo: add your logic here and delete this line
	if in.Password == "" && in.SendSms == "" {
		return nil, fmt.Errorf("请选择一种登录方式")
	}
	result, _ := cache.Rdb.Get(cache.Ctx, "send"+in.Mobile).Result()
	var user mysql.User
	mysql.DB.Debug().Where("mobile = ?", in.Mobile).Find(&user)
	if user.ID == 0 {
		if in.SendSms != result {
			return nil, fmt.Errorf("验证码错误,注册失败")
		}
		user.Mobile = in.Mobile
		user.Password = in.Password
		user.HeadImg = "https://cn.bing.com/images/search?q=%E9%BB%98%E8%AE%A4%E5%A4%B4%E5%83%8F&FORM=IQFRBA&id=E5E80050344E688E1EB01ACCDA37300A4927DA23"
		user.Name = fmt.Sprintf("默认用户昵称" + strconv.Itoa(rand.Intn(9000)+1000))
		mysql.DB.Debug().Create(&user)
	}
	if in.SendSms == "" {
		if in.Password != user.Password {
			return nil, fmt.Errorf("密码错误,登录失败")
		}
	}
	if in.Password == "" {
		if in.SendSms != result {
			return nil, fmt.Errorf("验证码错误,登录失败")
		}
	}
	return &houserpc.LoginResponse{UserId: int64(user.ID)}, nil
}
